<template>
  <el-dialog :title="title" v-model="visible" :destroy-on-close="true">
    <el-form :model="data" :rules="rules" ref="formRef" label-width="80px">
      <el-form-item label="试卷名称" prop="name">
        <el-input type="text" v-model="data.name"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="create" v-if="data.id === 0">添 加</el-button>
        <el-button type="primary" @click="update" v-if="data.id > 0">修 改</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import server from '@/utils/server'

import { type FormInstance, ElMessage } from 'element-plus'
import { cloneDeep } from 'lodash-es'

interface Paper {
  id: number
  examId: number
  name: string
}

const visible = ref(false)
const formRef = ref<FormInstance>()
const data = ref<Paper>({
  id: 0,
  examId: 0,
  name: ''
})
const title = data.value.id === 0 ? '创建试卷' : '修改试卷'
const rules = {
  name: [{ required: 'true', message: '名称不能为空', trigger: ['change'] }]
}

// 开启弹窗
const open = async (examId: number, id: number) => {
  visible.value = true
  data.value = {
    id: id,
    examId: examId,
    name: ''
  }
  if (id > 0) {
    data.value = (await server.get(`/writer/exam/paper/info?id=${id}`)) as Paper
  }
}
// 关闭弹窗
const close = () => {
  visible.value = false
}

// 通知重新装在数据
const emits = defineEmits(['reload'])
const create = async () => {
  formRef.value?.validate(async (valid: boolean) => {
    if (!valid) {
      return
    }
    const res = await server.post('/writer/exam/paper/create', data.value).then(() => {
      ElMessage.success('创建成功')
      close()
      emits('reload')
    })
  })
}

const update = async () => {
  formRef.value?.validate(async (valid: boolean) => {
    if (!valid) {
      return
    }
    const res = await server.post('/writer/exam/paper/update', data.value).then(() => {
      ElMessage.success('修改成功')
      close()
      emits('reload')
    })
  })
}
defineExpose({ open, close })
</script>

<style scoped></style>
